package com.binarycube.webserver.datasource;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import com.binarycube.cubedata.csv.CSVReader;
import com.binarycube.webserver.config.DatasourceConfig;

public class CSVDataSource extends AbstractDataSource implements IDataSource{
	static Logger log = Logger.getLogger(CSVDataSource.class.getName());
	
	public List<Record> doQuery() {
		validateParams();
		BufferedReader abc;
		try {
			abc = new BufferedReader(new FileReader(_config.getProperty("file")));
			CSVReader csvReader = new CSVReader(abc,CSVReader.HAS_HEADER);
			List<String[]> csvFile = csvReader.readAll();
			for (String[] line : csvFile) {
				Record r = Record.IndexedRecord();
				r.set(line);
				_records.add(r);
			}
			
			abc.close();
		} catch (IOException e) {
			log.error("Error configuring CSV Datasource: " + _config.getName(), e);
		}
		return _records;
	}
	
	public void configure(DatasourceConfig config) {
		super.configure(config);
		if (!new File(_config.getProperty("file")).exists()) {
			log.error("Error configuring CSV Datasource - file not found: " + _config.getName());
		}
	}


	

}
